package com.joshondesign.sdljava.gfx;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * Created by IntelliJ IDEA.
 * User: josh
 * Date: 9/9/11
 * Time: 4:14 PM
 * To change this template use File | Settings | File Templates.
 */
public class PropAnimation extends Animation {
    private Object target;
    private String propName;
    private int startValue;
    private int endValue;
    private double duration;

    public PropAnimation(Object target, String propName, int startValue, int endValue, double duration) {
        super();
        this.target = target;
        this.propName = propName;
        this.startValue = startValue;
        this.endValue = endValue;
        this.duration = duration;

    }

    public double getDuration() {
        return duration;
    }

    public int getStartValue() {
        return startValue;
    }

    public int getEndValue() {
        return endValue;
    }

    public void setCurrentValue(double currentValue) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        if(Util.AVIAN_WORKAROUND) {
            if(target instanceof Rect) {
                Rect t = (Rect) target;
                if("x".equals(propName)) {
                    t.setX(currentValue);
                    return;
                }
            }
        }
        Util.p("setting value to " + currentValue);
        String setter = "set" + propName.substring(0,1).toUpperCase() + propName.substring(1);
        Method setMethod = this.target.getClass().getMethod(setter, double.class);
        Object o = setMethod.invoke(this.target,new Object[]{currentValue});
        //Util.p("set value. return was: " + o);
    }


    @Override
    public void update(long currentTime) throws Exception {
        double fract = ((double)(currentTime-getStartTime()) / ((double)(getDuration()*1000)));
        if(fract > 1) {
            fract = 1.0;
            double currentValue = fract*(getEndValue()-getStartValue())+getStartValue();
            setCurrentValue(currentValue);
            stop();
        } else {
            double currentValue = fract*(getEndValue()-getStartValue())+getStartValue();
            setCurrentValue(currentValue);
        }

    }
}
